//
//  SearchView.swift
//  OnceNectar
//
//  Created by 法正磊 on 2018/2/4.
//  Copyright © 2018年 com.inwhoop. All rights reserved.
//

import UIKit

protocol SearchViewDelegate: NSObjectProtocol {
    func deleteHistoryData(index: NSInteger)
}

struct SearchViewData {
    var information: [ArticleModel] = []
    var video: [VideoModel] = []
    var circle: [CircleModel] = []
    var buy: [GoodsModel] = []
    var user: [UserInfoModel] = []
    var recommend: [SearchRecommendModel] = []
    var type: SearchViewType = .information
    
}

enum SearchViewType: Int {
    case information
    case video
    case circle
    case buy
    case user
}

class SearchView: BaseCircleView, ImageFactory, UITableViewDelegate, UITableViewDataSource, AddCornerUIRectCorner {
    
    private let bottomHeight: CGFloat = 40
    private let buttonHeight: CGFloat = 35
    private let topView = UIView()
    private let bottomViewHeight: CGFloat = 38
    private var tapIndex: ((NSInteger) -> Void)?
    private let mainTableView = UITableView()
    private var historyData: SearchViewData = SearchViewData()
    private var identifier: String = "information"
    private var beforButton: UIButton?
    private var buttenTitles: [String] = []
    private var bottomButton: UIButton = UIButton()
    var index: NSInteger = 0 {
        willSet {
            var titleImageName = newValue == 0 ? "icon_delete" : "bottom_button_ico"
            
            self.bottomButton.setTitle(newValue == 0 ? "清空历史搜索" : "", for: .normal)
            self.bottomButton.setImage(UIImage(named: titleImageName), for: .normal)
        }
    }
    var emptyView: UIView = UIView()
    weak var delegate: SearchViewDelegate?
    override init(frame: CGRect) {
        super.init(frame: frame)
        
    }
    
    override func awakeFromNib() {
        setUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    func show(titles: [String], datas: SearchViewData, tapIndex: @escaping (NSInteger) -> Void) {
        buttenTitles = titles
        setUI()
        self.tapIndex = tapIndex
//        historyData = datas
//        emptyView.isHidden = !historyData.information.isEmpty
//        setIdentifier()
//        mainTableView.reloadData()
    }
    func updataTableView(datas: SearchViewData,selectIndex:Int) -> Void {
        historyData = datas
        historyData.type = SearchViewType(rawValue: selectIndex)!
        print(historyData)
        mainTableView.reloadData()
        switch historyData.type {
        case .information:
            emptyView.isHidden = !historyData.information.isEmpty

        case .video:
            emptyView.isHidden = !historyData.video.isEmpty

        case .circle:
            emptyView.isHidden = !historyData.circle.isEmpty

        case .buy:
            emptyView.isHidden = !historyData.buy.isEmpty
            
        case .user:
            emptyView.isHidden = !historyData.buy.isEmpty
            
        default:
            break
        }
    }
    private func setUI() {
//        self.layoutIfNeeded()
        DispatchQueue.global().asyncAfter(deadline: DispatchTime.now() + 0.1) {
            DispatchQueue.main.async {
                self.topView.frame = CGRect(x: 0, y: 0, width: self.width, height: self.buttonHeight + 20)
                self.topView.backgroundColor = UIColor(hex: 0xC4C4C4)
                self.addSubview(self.topView)
                
                for (index, title) in self.buttenTitles.enumerated() {
                    let button = UIButton(type: .custom)
                    let buttonWidth: CGFloat = self.width / CGFloat(self.buttenTitles.count)
                    button.frame = CGRect(x: CGFloat(index) * buttonWidth, y: 0, width: buttonWidth, height: self.buttonHeight)
                    button.tag = index
                    button.addTarget(self, action: #selector(self.selectTap(_ :)), for: .touchUpInside)
                    self.addCornerWithView(aView: button, aCorners: [.topLeft, .topRight], aSize: CGSize(width: CORNERRADIUS, height: CORNERRADIUS))
                    button.setBackgroundImage(self.createImage(color: UIColor(hex: 0xC4C4C4), height: self.buttonHeight), for: .normal)
                    button.adjustsImageWhenHighlighted = false;
                    button.adjustsImageWhenDisabled = false;
                    button.setBackgroundImage(self.createImage(color: UIColor.white, height: self.buttonHeight), for: .selected)
                    button.setTitle(title, for: .normal)
                    button.setTitleColor(ONColor.searchScreenTitleNormalColor, for: .normal)
                    button.setTitleColor(UIColor.black, for: .selected)
                    button.titleLabel?.font = UIFont.systemFont(ofSize: 14)
                    if index == 0 {
                        self.beforButton = button
                        button.isSelected = true
                    }
                    
                    self.topView.addSubview(button)
                }
                
                self.mainTableView.delegate = self
                self.mainTableView.dataSource = self
                self.mainTableView.separatorStyle = .none
//                self.mainTableView.bounces = false
                self.mainTableView.backgroundColor = UIColor.red
                self.backgroundColor = UIColor.green
                //                self.mainTableView.register(UINib(nibName: "\(SearchHistoryTableViewCell.self)", bundle: nil), forCellReuseIdentifier: "information")
                self.mainTableView.register(UINib(nibName: "\(SearchInformationTableViewCell.self)", bundle: nil), forCellReuseIdentifier: "information")
                self.mainTableView.register(UINib(nibName: "\(SearchUserTableViewCell.self)", bundle: nil), forCellReuseIdentifier: "user")
                if #available(iOS 11.0, *) {
                    self.mainTableView.contentInsetAdjustmentBehavior = .never
                } else {
                    // Fallback on earlier versions
                }
                self.mainTableView.frame = CGRect(x: 0, y: self.buttonHeight, width: self.width, height: self.height - self.bottomViewHeight - self.buttonHeight)
                
                self.addSubview(self.mainTableView)
                
//                self.mainTableView.addSubview(self.emptyView)
//                self.emptyView.frame = self.mainTableView.bounds
//                let imageView = UIImageView(image: UIImage(named: "empyt_icon"))
//                imageView.center = CGPoint(x: self.emptyView.width / 2, y: self.emptyView.height / 2)
//                self.emptyView.addSubview(imageView)
//
//                let emptyLabel = UILabel()
//                emptyLabel.text = "暂无相关内容"
//                self.emptyView.addSubview(emptyLabel)
//                emptyLabel.snp.makeConstraints({ (make) in
//                    make.top.equalTo(imageView.snp.bottom).offset(10)
//                    make.centerX.equalTo(imageView.snp.centerX)
//                })
//
//                self.bottomButton = UIButton(type: .custom)
//                self.bottomButton.frame = CGRect(x: 0, y: self.height - self.bottomViewHeight, width: self.width, height: self.bottomViewHeight)
//                self.bottomButton.backgroundColor = ONColor.searchButtomColor
//                self.bottomButton.setTitle("清空历史搜索", for: .normal)
//                self.bottomButton.titleLabel?.font = UIFont.systemFont(ofSize: 15)
//                self.bottomButton.imageEdgeInsets = UIEdgeInsetsMake(0, -6, 0, 0)
//                self.bottomButton.setImage(UIImage(named: "icon_delete"), for: .normal)
//                self.addSubview( self.bottomButton)
            }
        }
    }
    
    @objc func selectTap(_ btn: UIButton) {
//        if btn.tag != 0 {
//            emptyView.isHidden = true
//        } else {
//            emptyView.isHidden = historyData.information.isEmpty ? false : true
//        }
        
        if let button = self.beforButton {
            if button != btn {
                button.isSelected = false
            }
        }
        btn.isSelected = true
        self.beforButton = btn
//        mainTableView.layer.mask?.removeFromSuperlayer()
        var corner: UIRectCorner!
        switch btn.tag {
        case 0:
            corner = .topRight
        case 4:
            corner = .topLeft
        default:
            corner = [.topRight, .topLeft]
        }
        
        addCornerWithView(aView: self.mainTableView, aCorners: corner, aSize: CGSize(width: CORNERRADIUS, height: CORNERRADIUS))
        historyData.type = SearchViewType(rawValue: btn.tag)!
//        self.tapIndex?(btn.tag)
//        setIdentifier()
//        mainTableView.reloadData()
    }
    
    // MARK: - tableViewDataSource
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        switch historyData.type {
        case .buy:
            return 20//historyData.buy.count
        case .circle:
            return 20//historyData.circle.count
        case .information:
            return 20//historyData.information.count
        case .user:
            return 20//historyData.user.count
        case .video:
            return 20//historyData.video.count
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: identifier)
        /*
        switch historyData.type {
        case .circle:
            let c = cell as? SearchInformationTableViewCell
//            let circleModel = historyData.circle[indexPath.row]
//            c?.contentLabel.text = circleModel.circleName!
//            let path:String = "\(BaseURL)\(circleModel.coverPath!)"
//            
//
//            let url = NSURL.init(string: path.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)
//
//            c?.showImageView.sd_setAnimationImages(with: [url! as URL])

        case .video:
            let c = cell as? SearchInformationTableViewCell
//            let videoModel = historyData.video[indexPath.row]
//            c?.contentLabel.text = videoModel.title!
//            let path:String = "\(BaseURL)\(videoModel.coverImgPath!)"
//            
//
//            let url = NSURL.init(string: path.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)
//
//            c?.showImageView.sd_setAnimationImages(with: [url! as URL])
            
        case .buy:
            let c = cell as? SearchInformationTableViewCell
//            let buyModel = historyData.buy[indexPath.row]
//            c?.contentLabel.text = buyModel.goodsName!
//            let path:String = "\(BaseURL)\(buyModel.coverPath!)"
//            
//
//            let url = NSURL.init(string: path.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)
//
//            c?.showImageView.sd_setAnimationImages(with: [url! as URL])
            
        case .information:
            let c = cell as? SearchInformationTableViewCell
//            let articleModel = historyData.information[indexPath.row]
//            c?.contentLabel.text = articleModel.title!
//            let path:String = "\(BaseURL)\(articleModel.coverImgPath!)"
//            
//
//            let url = NSURL.init(string: path.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)
//
//            c?.showImageView.sd_setAnimationImages(with: [url! as URL])
            
            
            //            let c = cell as? SearchHistoryTableViewCell
            //            c?.delegate = self
            //            let articleModel = historyData.information[indexPath.row]
        //            c?.dataLabel.text = articleModel.title!
        case .user:
            let c = cell as? SearchUserTableViewCell
//            let userModel = historyData.user[indexPath.row]
//            c?.nameLabel.text = userModel.username!
//            c?.levelLabel.text = userModel.level!
//            c?.matchLabel.text = userModel.matchDegree!
            
        default:
            break
        }*/
        return cell!
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        switch historyData.type {
        case .buy:
            return 135
        case .circle:
            return 135
        case .information:
            return 135
        case .user:
            return 85.5
        case .video:
            return 135
        }
    }
//
//    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
//        switch historyData.type {
//        case .buy:
//            return UIView()
//        case .circle:
//            return UIView()
//        case .information:
//            //            let view = UIView(frame: CGRect(x: 0, y: 0, width: tableView.width, height: bottomHeight))
//            //            let label = UILabel()
//            //            label.text = "历史记录"
//            //            label.sizeToFit()
//            //            label.center.y = view.height / 2
//            //            label.frame.origin.x = 18
//            //            view.addSubview(label)
//            //            return view
//            return UIView()
//        case .user:
//            return nil
//        case .video:
//            return UIView()
//        }
//    }
    
//    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
//        switch historyData.type {
//        case .buy:
//            return 20
//        case .circle:
//            return 20
//        case .information:
//            return 20
//        case .user:
//            return 10
//        case .video:
//            return 20
//        }
//    }
    
    // MARK: - searchHistoryDedeleteButtonTap
//    func searchHistoryDedeleteButtonTap(_ cell: SearchHistoryTableViewCell) {
//        let indexPath = mainTableView.indexPath(for: cell)
//        historyData.information.remove(at: indexPath!.row)
//        mainTableView.reloadData()
//        self.delegate?.deleteHistoryData(index: indexPath!.row)
//    }
}
//
//extension SearchView {
//    func setIdentifier() {
//        switch historyData.type {
//        case .buy:
//            identifier = "information"
//        case .circle:
//            identifier = "information"
//        case .information:
//            identifier = "information"
//        case .user:
//            identifier = "user"
//        case .video:
//            identifier = "information"
//        }
//    }
//}

